﻿namespace TheCodeWerks.Advertising
{
	using System;
	using System.Collections.Generic;
	using System.Linq;

	public class PercentageSelector : IWeightedSelector
	{
		private Random random = new Random();

		public AdUnit Select(List<AdUnit> units)
		{
			if (units.Count == 1) return units[0];

			var total = units.Sum(item => item.Weight);
			var value = random.NextDouble();
			var perecentage = units[0].Weight;

			for (int index = 0; index < units.Count; index++)
			{
				var item = units[index];

				if (value < perecentage) return item;

				perecentage += item.Weight;
			}

			return units[0];
		}
	}
}
